package org.codeart.pay.controller;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import lombok.extern.slf4j.Slf4j;
import org.codeart.pay.service.AliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/alipay")
public class AliPayController {

    @Autowired
    private AliPayService aliPayService;

    @GetMapping("/pay")
    public String pay(String subject, String outTradeNo, String totalAmount) {
        AlipayTradePagePayResponse response = null;
        try {
            response = Factory.Payment.Page().pay(subject, outTradeNo, totalAmount, "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response.getBody();
    }

    @PostMapping("/notify")
    public String notifyCallback(HttpServletRequest request) throws Exception {
        log.info("收到支付宝的回调信息");
        String tradeStatus = request.getParameter("trade_status");
        if ("TRADE_SUCCESS".equals(tradeStatus.trim())) {
            Map<String, String> param = new HashMap<>();
            Map<String, String[]> parameterMap = request.getParameterMap();
            for (String name : parameterMap.keySet()) {
                param.put(name, request.getParameter(name));
            }

            if (Factory.Payment.Common().verifyNotify(param)) {
                System.out.println("通过支付宝的验证");
                String outTradeNo = param.get("out_trade_no");
                Long orderId = Long.parseLong(outTradeNo);
                boolean b = aliPayService.pay(orderId);
                if (b) {
                    log.info("订单状态更新完成!");
                } else {
                    log.info("订单状态更新异常，请检查系统!");
                }
            } else {
                System.out.println("支付宝验证不通过！");
            }
        }
        return "支付宝回调测试";
    }
}
